<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
             label-width="120px">
      <!--      <el-form-item label="课题组id" prop="teamId">
              <el-input v-model="dataForm.teamId" placeholder="课题组id"></el-input>
            </el-form-item>
            <el-form-item label="用户id" prop="userId">
              <el-input v-model="dataForm.userId" placeholder="用户id"></el-input>
            </el-form-item>-->
      <el-form-item label="用户名称" prop="userId" :class="{ 'is-required': true }">
        <el-select v-model="dataForm.userId" style="width: 250px" filterable remote reserve-keyword
                   placeholder="输入手机号或姓名" :remote-method="getUserList" :loading="loading" @change="changeUser">
          <el-option v-for="item in userList" :key="item.value" :label="item.username + '-' + item.mobile"
                     :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="状态" prop="status">
              <el-radio-group v-model="dataForm.status">
                <el-radio :label="0">申请</el-radio>
                <el-radio :label="1">通过</el-radio>
              </el-radio-group>
            </el-form-item>-->
      <!--<el-form-item label="是否创建者：0否，1是" prop="isCreator">
        <el-input v-model="dataForm.isCreator" placeholder="是否创建者：0否，1是"></el-input>
      </el-form-item>-->
      <el-form-item label="审核权限" prop="approve">
        <el-radio-group v-model="dataForm.approve">
          <el-radio :label="0">无</el-radio>
          <el-radio :label="1">有</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="查看权限" prop="viewPower">
        <el-radio-group v-model="dataForm.viewPower">
          <el-radio :label="0">自己</el-radio>
          <el-radio :label="1">所有</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="金额权限" prop="amountPower">
        <el-radio-group v-model="dataForm.amountPower">
          <el-radio :label="0">无</el-radio>
          <el-radio :label="1">固定</el-radio>
          <el-radio :label="2">所有</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="dataForm.amountPower == 1" label="可用金额" prop="debtLimit">
        <el-input type="number" max="99999999.99" v-model="dataForm.debtLimit" placeholder="可用金额"
                  @input="dataForm.debtLimit = Math.min(dataForm.debtLimit, 99999999.99)"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, ref} from "vue";
import baseService from "@/service/baseService";
import {ElMessage} from "element-plus";

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const userList = ref<any[]>([]);
const loading = ref(false);

const dataForm = reactive({
  id: "",
  teamId: "",
  teamName: "",
  userId: "",
  username: "",
  status: "",
  approve: 0,
  viewPower: 0,
  amountPower: 0,
  debtLimit: 0
});

const validateUser = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (!/\S/.test(value)) {
    return callback(new Error("必填项不能为空"));
  }
  if (!dataForm.id) {
    baseService
      .get("/yckj/teamrelation/list", {
        teamId: dataForm.teamId,
        userId: dataForm.userId
      })
      .then((res) => {
        if (res.data.length > 0) {
          return callback(new Error("当前用户已添加"));
        }
      });
  }
  callback();
};

const rules = ref({
  // teamId: [
  //   {required: true, message: '必填项不能为空', trigger: 'blur'}
  // ],
  userId: [{validator: validateUser, trigger: "blur"}],
  // username: [
  //   {required: true, message: '必填项不能为空', trigger: 'blur'}
  // ],
  approve: [{required: true, message: "必填项不能为空", trigger: "blur"}],
  viewPower: [{required: true, message: "必填项不能为空", trigger: "blur"}],
  amountPower: [{required: true, message: "必填项n不能为空", trigger: "blur"}]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getUserList("")]).then(() => {
    if (id) {
      getInfo(id);
    }
  });
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/yckj/teamrelation/" + id).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 获取用户列表
const getUserList = async (query: string) => {
  loading.value = true;
  const res = await baseService.get("/yckj/user/list", {key: query});
  userList.value = res.data;
  loading.value = false;
};

const changeUser = (value: number) => {
  const selectedItem = userList.value.find((item) => item.id === value);
  dataForm.username = selectedItem.username;
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    if (dataForm.amountPower != 1) {
      dataForm.debtLimit = 0;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/yckj/teamrelation", dataForm).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init,
  dataForm
});
</script>
